// @flow
import React, { Component } from 'react'
import styles from './TaskEdit.css'
import { Form, Input, Button, Select, message } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const FormItem = Form.Item
const Option = Select.Option
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}
type Props = {
  form: Object,
  history: Object
}

type States = {
  industries: Array<Object>,
  customerTypes: Array<Object>,
  loading: boolean,
  provinces: Array<Object>,
  districts: Array<Object>,
  cities: Array<Object>,
  customerData: Object,
  province: string,
  city: string,
  district: string
}
class TaskEdit1 extends Component {
  props: Props
  state: States
  getIndustry: Function
  getCustomerType: Function
  getProvinces: Function
  submit: Function
  goBack: Function
  changeProvince: Function
  changeCity: Function
  getCities: Function
  getDistricts: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      industries: [],
      customerTypes: [],
      loading: false,
      provinces: [],
      districts: [],
      cities: [],
      customerData: {},
      province: '',
      city: '',
      district: ''
    }

    this.getIndustry = this.getIndustry.bind(this)
    this.getCustomerType = this.getCustomerType.bind(this)
    this.submit = this.submit.bind(this)
    this.goBack = this.goBack.bind(this)
    this.changeProvince = this.changeProvince.bind(this)
    this.getProvinces = this.getProvinces.bind(this)
    this.changeCity = this.changeCity.bind(this)
    this.getCities = this.getCities.bind(this)
    this.getDistricts = this.getDistricts.bind(this)
  }

  componentWillMount () {
    this.getIndustry()
    this.getCustomerType()
    const { data } = this.props.history.location.state
    this.setState({
      customerData: data,
      province: data.region.province,
      city: data.region.city,
      district: data.region.district
    })
    this.getProvinces()
    this.getCities(data.region.province)
    this.getDistricts(data.region.province, data.region.city)
  }

  getProvinces () {
    universalFetch(`${__SERVICE_API__}sys/regions/province`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          provinces: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getCities (province) {
    universalFetch(`${__SERVICE_API__}sys/regions/city?province=${province}`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }

      this.setState({
        cities: json.result
      })
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  getDistricts (province, city) {
    universalFetch(`${__SERVICE_API__}sys/regions/district?province=${province}&city=${city}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }

        this.setState({
          districts: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getIndustry () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=industry`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          industries: json.result.industry
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getCustomerType () {
    universalFetch(`${__SERVICE_API__}device/conditions?types=customerType`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          customerTypes: json.result.customerType
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  changeProvince (value) {
    universalFetch(`${__SERVICE_API__}sys/regions/city?province=${value}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }

        this.props.form.setFieldsValue({ city: '' })
        this.props.form.setFieldsValue({ district: '' })
        this.setState({
          cities: json.result,
          city: '',
          district: '',
          province: value
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  changeCity (value) {
    const { getFieldsValue, setFieldsValue } = this.props.form
    const { province } = getFieldsValue()
    universalFetch(`${__SERVICE_API__}sys/regions/district?province=${province}&city=${value}`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }

        this.setState({
          city: value,
          districts: json.result,
          district: ''
        })
        setFieldsValue({ district: '' })
        // resetFields(['district'])
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  submit () {
    const { form } = this.props
    form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const values = {
        ...fieldsValue
      }

      const { customerData } = this.state

      universalFetch(`${__SERVICE_API__}device/customers/${customerData.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(values)
      })
        .then(res => res.json())
        .then((json) => {
          if (json.code !== 200000) {
            throw new Error(JSON.stringify({ code: json.code, message: json.message }))
          }
          this.setState({
            loading: false
          })
          message.success('客户修改成功')
          this.props.history.push('/business/customer')
        })
        .catch((error) => {
          handleFetchError(error)
          console.error(error)
          message.error('客户修改失败')
          this.setState({
            loading: false
          })
        })
    })
  }

  goBack () {
    this.props.history.push('/business/customer')
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { industries, customerTypes, loading, provinces,
      cities, districts, customerData, city, district
     } = this.state
    const cityDecorator = city
    ? getFieldDecorator('city', {
      initialValue: city
    })
    : getFieldDecorator('city', {
    })

    const districtDecorator = district
    ? getFieldDecorator('district', {
      initialValue: district
    })
    : getFieldDecorator('district', {})
    return (
      <div className={styles['main']}>
        <Form>
          <FormItem {...formItemLayout} label='客户编号' hasFeedback>
            {
              getFieldDecorator('customerNo', {
                rules: [
                  { required: true, message: '请填写客户编号', whitespace: true }
                ],
                initialValue: customerData.customerNo
              })(
                <Input placeholder='请填写客户编号' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='客户名称' hasFeedback>
            {
              getFieldDecorator('name', {
                rules: [
                  { required: true, message: '请填写客户名称', whitespace: true }
                ],
                initialValue: customerData.name
              })(
                <Input placeholder='请填写客户名称' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='省'>
            {
              getFieldDecorator('province', {
                rules: [
                  { required: true, message: '请选择省' }
                ],
                initialValue: customerData.region.province
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择省' onChange={this.changeProvince}>
                  {
                    provinces.map((province, i) => {
                      return <Option key={i} value={province.province}>
                        {province.province}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='市'>
            {
              cityDecorator(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择市' onChange={this.changeCity}>
                  {
                    cities.map((city, i) => {
                      return <Option key={i} value={city.city}>
                        {city.city}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='区'>
            {
              districtDecorator(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择区'>
                  {
                    districts.map((district, i) => {
                      return <Option key={i} value={district.district}>
                        {district.district}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='所属行业'>
            {
              getFieldDecorator('industry', {
                initialValue: customerData.industry
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择所属行业'>
                  {
                    industries.map((item, i) => {
                      return <Option key={i} value={item.value}>
                        {item.label}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='客户类型'>
            {
              getFieldDecorator('type', {
                initialValue: customerData.type
              })(
                <Select showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} placeholder='请选择客户类型'>
                  {
                    customerTypes.map((item, i) => {
                      return <Option key={i} value={item.value}>
                        {item.label}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='联系人' hasFeedback>
            {
              getFieldDecorator('contactPerson', {})(
                <Input placeholder='请填写联系人' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='联系方式' hasFeedback>
            {
              getFieldDecorator('mobile', {})(
                <Input placeholder='请填写联系方式' />
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='详细地址' hasFeedback>
            {
              getFieldDecorator('address', {})(
                <Input placeholder='请填写详细地址' />
              )
            }
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary'
              loading={loading}
              onClick={this.submit}
              >
              保存
            </Button>
            <Button
              onClick={this.goBack}
              style={{ marginLeft: '20px' }}
              >
              返回
            </Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

export default Form.create()(TaskEdit1)
